package com.nosnow.gmall.item.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.nosnow.gmall.bean.SkuInfo;
import com.nosnow.gmall.bean.SkuSaleAttrValue;
import com.nosnow.gmall.bean.SpuSaleAttr;
import com.nosnow.gmall.service.ListService;
import com.nosnow.gmall.service.ManageService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 说明：item模块
 */
@Controller
public class ItemController {

    @Reference
    private ManageService manageService;

    @Reference
    private ListService listService;

    @RequestMapping("{skuId}.html")
    public String getSkuInfo(@PathVariable("skuId") String skuId, Model model) {
        SkuInfo skuInfo = manageService.getSkuInfo(skuId);
        model.addAttribute("skuInfo", skuInfo);

        List<SpuSaleAttr> saleAttrList = manageService.getSpuSaleAttrListCheckBySku(skuInfo);
        model.addAttribute("saleAttrList", saleAttrList);

        List<SkuSaleAttrValue> skuSaleAttrValueListBySpu = manageService.getSkuSaleAttrValueListBySpu(skuInfo.getSpuId());
        // 将列表转换成 valueid1|valueid2|valueid3 ：skuId  的哈希表，用于在此页面中定位查询
        String valueIdsKey="";
        Map<String, String> valuesSkuMap = new HashMap<>(16);
        for (int i = 0; i < skuSaleAttrValueListBySpu.size(); i++) {
            SkuSaleAttrValue skuSaleAttrValue = skuSaleAttrValueListBySpu.get(i);
            if(valueIdsKey.length()!=0) {
                valueIdsKey= valueIdsKey+"|";
            }
            valueIdsKey = valueIdsKey + skuSaleAttrValue.getSaleAttrValueId();
            if((i + 1) == skuSaleAttrValueListBySpu.size() || !skuSaleAttrValue.getSkuId().equals(skuSaleAttrValueListBySpu.get(i+1).getSkuId())) {
                valuesSkuMap.put(valueIdsKey, skuSaleAttrValue.getSkuId().toString());
                valueIdsKey="";
            }
        }

        // 将Map转换为JSON
        String valuesSkuJson = JSON.toJSONString(valuesSkuMap);
        model.addAttribute("valuesSkuJson",valuesSkuJson);


        listService.incrHotScore(skuId);
        return "item";
    }


}
